// 门店数据页面混入
import {
	getMockStoreDataList,
	exportStoreData
} from '../api/storeData'

export default {
	data() {
		return {
			// 页面状态
			loading: false,
			refreshing: false,
			loadingMore: false,
			hasMore: true,
			
			// 搜索和筛选
			searchKeyword: '',
			activeFilterTab: 0,
			filterTabs: [
				{ name: '全部', value: 'all' },
				{ name: '有退货', value: 'hasReturn' },
				{ name: '无退货', value: 'noReturn' }
			],
			
			// 分页参数
			currentPage: 1,
			pageSize: 20,
			
			// 数据列表
			dataList: [],
			filteredList: [],
			displayList: []
		}
	},
	
	computed: {
		// 总商品数
		totalProducts() {
			return this.displayList.length
		},
		
		// 总采购件数
		totalPurchase() {
			return this.displayList.reduce((sum, item) => sum + item.purchaseCount, 0)
		},
		
		// 总退货件数
		totalReturn() {
			return this.displayList.reduce((sum, item) => sum + item.returnCount, 0)
		}
	},
	
	onLoad() {
		this.initPage()
	},
	
	onPullDownRefresh() {
		this.onRefresh()
	},
	
	onReachBottom() {
		this.loadMore()
	},
	
	methods: {
		// 初始化页面
		async initPage() {
			this.loading = true
			try {
				await this.loadStoreData()
			} catch (error) {
				console.error('初始化页面失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 加载门店数据
		async loadStoreData(isLoadMore = false) {
			try {
				const params = {
					page: isLoadMore ? this.currentPage + 1 : 1,
					pageSize: this.pageSize,
					keyword: this.searchKeyword,
					filter: this.filterTabs[this.activeFilterTab].value
				}
				
				const res = await getMockStoreDataList(params)
				
				if (res.code === 200) {
					const newData = res.data.list || []
					
					if (isLoadMore) {
						this.dataList = [...this.dataList, ...newData]
						this.currentPage += 1
					} else {
						this.dataList = newData
						this.currentPage = 1
					}
					
					// 检查是否还有更多数据
					this.hasMore = newData.length === this.pageSize
					
					// 应用筛选和搜索
					this.applyFilters()
				}
			} catch (error) {
				console.error('加载门店数据失败:', error)
				throw error
			}
		},
		
		// 应用筛选和搜索
		applyFilters() {
			let filtered = [...this.dataList]
			
			// 搜索筛选
			if (this.searchKeyword) {
				const keyword = this.searchKeyword.toLowerCase()
				filtered = filtered.filter(item => 
					item.productName.toLowerCase().includes(keyword) ||
					item.productCode.toLowerCase().includes(keyword)
				)
			}
			
			// 分类筛选
			const filterValue = this.filterTabs[this.activeFilterTab].value
			if (filterValue === 'hasReturn') {
				filtered = filtered.filter(item => item.returnCount > 0)
			} else if (filterValue === 'noReturn') {
				filtered = filtered.filter(item => item.returnCount === 0)
			}
			
			this.filteredList = filtered
			this.displayList = filtered
		},
		
		// 刷新数据
		async onRefresh() {
			this.refreshing = true
			try {
				this.currentPage = 1
				this.hasMore = true
				await this.loadStoreData()
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('刷新数据失败:', error)
				this.showError('刷新失败')
			} finally {
				this.refreshing = false
				uni.stopPullDownRefresh()
			}
		},
		
		// 加载更多
		async loadMore() {
			if (this.loadingMore || !this.hasMore) return
			
			this.loadingMore = true
			try {
				await this.loadStoreData(true)
			} catch (error) {
				console.error('加载更多失败:', error)
				this.showError('加载失败')
			} finally {
				this.loadingMore = false
			}
		},
		
		// 搜索处理
		handleSearch() {
			// 防抖处理
			clearTimeout(this.searchTimer)
			this.searchTimer = setTimeout(() => {
				this.applyFilters()
			}, 300)
		},
		
		// 清除搜索
		clearSearch() {
			this.searchKeyword = ''
			this.applyFilters()
		},
		
		// 切换筛选标签
		async switchFilterTab(index) {
			if (this.activeFilterTab === index) return
			
			this.activeFilterTab = index
			this.loading = true
			try {
				await this.loadStoreData()
			} catch (error) {
				console.error('切换筛选失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 刷新数据
		async refreshData() {
			this.loading = true
			try {
				await this.loadStoreData()
			} catch (error) {
				console.error('刷新数据失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 导出数据
		async handleExport() {
			try {
				uni.showLoading({
					title: '导出中...'
				})
				
				const params = {
					keyword: this.searchKeyword,
					filter: this.filterTabs[this.activeFilterTab].value,
					exportType: 'excel'
				}
				
				// 这里可以调用真实的导出API
				// const res = await exportStoreData(params)
				
				// 模拟导出过程
				setTimeout(() => {
					uni.hideLoading()
					uni.showToast({
						title: '导出成功',
						icon: 'success'
					})
				}, 2000)
				
			} catch (error) {
				uni.hideLoading()
				console.error('导出失败:', error)
				this.showError('导出失败')
			}
		},
		
		// 格式化数字
		formatNumber(num) {
			if (num === null || num === undefined) return '0'
			
			const number = parseFloat(num)
			if (isNaN(number)) return '0'
			
			return number.toLocaleString('zh-CN')
		},
		
		// 显示错误信息
		showError(message) {
			uni.showToast({
				title: message,
				icon: 'none',
				duration: 2000
			})
		}
	},
	
	// 页面卸载时清除定时器
	beforeDestroy() {
		if (this.searchTimer) {
			clearTimeout(this.searchTimer)
		}
	}
}
